<?php
/**
 * 	Portal
 *
 * @category   Portal
 * @package    Portal
 * @copyright  Copyright (c) 2009 Nathan Keyes
 * @author $Author: nkeyes $
 * @version    $Id: File.php 7 2009-11-14 22:42:08Z nkeyes $
 */
 
class Bushido_DbTable_Image extends Bushido_Db_Table_Abstract
{
	protected $_name = 'image';
	protected $_niceName = 'Image';
	protected $_sequence = true;
	
	protected $_referenceMap = array
	(	
		'ParentImage' => array
		(
			'columns' => 'parent_image_id',
			'refTableClass' => 'Bushido_DbTable_Image',
			'refColumns' => 'image_id'
		),
		
		'User' => array
		(
			'columns' => 'bushido_user_id',
			'refTableClass' => 'Bushido_DbTable_User',
			'refColumns' => 'bushido_user_id'
		),
		
		'Gallery' => array
		(
			'columns' => 'gallery_id',
			'refTableClass' => 'Bushido_DbTable_Gallery',
			'refColumns' => 'gallery_id'
		),
	);

	/**
	 * (non-PHPdoc)
	 * @see library/Bushido/Db/Table/Bushido_Db_Table_Abstract#_setFieldDetails()
	 */
	protected function _setFieldDetails()
	{
		//parent_image_id
		$this->_metadata['parent_image_id']['fieldDetails'] = array
		(
			'type' => 'generated',
		);
		
		//bushido_user_id
		$this->_metadata['bushido_user_id']['fieldDetails'] = array
		(
			'type' => 'generated',
			'defaultValue' => Bushido_App::session()->userInfo['bushido_user_id'],
		);
		
		//filename
		$this->_metadata['filename']['fieldDetails'] = array
		(
			'type' => 'generated'
		);
		
		//size
		$this->_metadata['size']['fieldDetails'] = array
		(
			'type' => 'generated'
		);
		
		//mime_type
		$this->_metadata['mime_type']['fieldDetails'] = array
		(
			'type' => 'generated'
		);
		
		//content
		$this->_metadata['content']['fieldDetails'] = array
		(
			'type' => 'File',
			'options' => array
			(
				'label' => 'File:'
			) 
		);
	}
	
	
	/**
	 * (non-PHPdoc)
	 * @see library/Bushido/Table/Bushido_Table_Abstract#getDisplayValue()
	 */
	public static function getDisplayValue(Zend_Db_Table_Row_Abstract $row, $context = null)
	{
		return $row->caption;
	}
	
	public function insert($data)
	{	
		$retVal =  parent::insert($data);
		
		if(!isset($data['parent_image_id'])) // this isn't a thumbnail
		{
			$imageData = $data['content'];
			$thumb = new Imagick();
			$thumb->readimageblob($imageData);
			$thumb->thumbnailImage(64,64,true);
			
			$data['filename'] = $data['filename'] . '_thumb';
			$data['content'] = $thumb->getimageblob();
			$data['parent_image_id'] = $retVal;
			$this->insert($data);
		}
		
		return $retVal;
	}
}